package com.example.rabbitmq.consumer;


import com.example.rabbitmq.config.RabbitMQConfiguration;
import com.example.rabbitmq.pojo.TestPojo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class TestConsumer {

    /**
     * 监听QUEUE_NAME队列是否有消息可以消费
     * 重试机制的测试
     * ackMode：默认NONE自动/MANUAL手动/AUTO容器根据正常返回还是抛出异常来发出ack/nack
     * 如果信道为自动true，则channel不能ack/nack等
     * containerFactory:设置为该消费者处理的容器
     * @param message 接受到该队列的消息
     */
    //DeliverCallback
    @RabbitListener(queues = {RabbitMQConfiguration.QUEUE_NAME},ackMode = "NONE",containerFactory = "customSimpleRabbitListenerContainerFactory")//相当于basicConsume
    public void ackCallbackQueue(TestPojo testPojo, Message message, Channel channel) throws IOException {
//        try {
//            throw new RuntimeException("测试重试机制");
//        } catch (Throwable throwable) {
//            throwable.printStackTrace();
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
//        }
        System.out.println("==========="+RabbitMQConfiguration.QUEUE_NAME+"================");
        Date date = new Date();
        System.out.println(date+"\t   消息："+new String(message.getBody(), StandardCharsets.UTF_8));
        //看看消息转换是否成功
        System.out.println(testPojo);
//        int i=10/0;
    }

    //死信消费者
    @RabbitListener(queues = {RabbitMQConfiguration.DEAD_QUEUE_NAME})//相当于basicConsume
    public void ackCallbackDeadQueue(Message message){
        System.out.println("==========="+RabbitMQConfiguration.DEAD_QUEUE_NAME+"================");
        Date date = new Date();
        System.out.println(date+"\t   消息："+new String(message.getBody(), StandardCharsets.UTF_8));
    }

    //备用消费者
    @RabbitListener(queues = {RabbitMQConfiguration.BACKUP_QUEUE_NAME})//相当于basicConsume
    public void ackCallbackBackupQueue(Message message){
        System.out.println("==========="+RabbitMQConfiguration.BACKUP_QUEUE_NAME+"================");
        Date date = new Date();
        System.out.println(date+"\t   消息："+new String(message.getBody(), StandardCharsets.UTF_8));
    }

}
